package org.ekstrabilet.main.gui.panes;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

import org.ekstrabilet.main.gui.MainWindow;
import org.ekstrabilet.main.gui.UserStates;
import org.ekstrabilet.user.beans.User;
import org.ekstrabilet.user.logic.UserLogic;

/**
 * Login pane GUI class.
 *
 */
public class InitPane {
	
	private MainWindow frame;
	/*
	 * GUI components
	 */
	private JPanel pane;
	private JPanel loginPane;
	private JLabel lLogin, lPass, lUser;
	private JTextField tfLogin;
	private JPasswordField pfPass;
	private JComboBox cUser;
	private JButton button;
	
	public String[] userTable = {Panes.GUEST, Panes.SALES, Panes.TECH, Panes.ADMIN};
	
	/**
	 * Default constructor.
	 * @param f reference to main window
	 */
	public InitPane(MainWindow f) {
		frame = f;
		initGUI();
	}

	private void initGUI() {
		lLogin = new JLabel("Login:  ", SwingConstants.LEFT);
		lPass = new JLabel("Password:  ");
		lUser = new JLabel("User:  ");
		
		tfLogin = new JTextField();
		
		pfPass = new JPasswordField();
		
		cUser = new JComboBox(userTable);
				
		button = new JButton("OK");
		button.addActionListener(new LoginListener());
		
		loginPane = new JPanel();
		loginPane.setLayout(new GridLayout(7, 1, 8, 8));
		loginPane.add(lLogin);
		loginPane.add(tfLogin);
		loginPane.add(lPass);
		loginPane.add(pfPass);
		loginPane.add(lUser);
		loginPane.add(cUser);
		loginPane.add(button);
		
		pane = new JPanel();
		pane.add(loginPane);
		
	}
	
	public JPanel getPane() {
		return pane;
	}
	
	private static int mapUserStates(String state) {
		if(state == null) return UserStates.ILLEGAL;
		
		if(state.equals(Panes.ADMIN)) return UserStates.ADMIN;
		if(state.equals(Panes.GUEST)) return UserStates.GUEST;
		if(state.equals(Panes.SALES)) return UserStates.SALES;
		if(state.equals(Panes.TECH)) return UserStates.TECH;
		
		return UserStates.ILLEGAL;
	}
	
	class LoginListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			
			String login = tfLogin.getText();
			String pass = new String(pfPass.getPassword());
			String type = (String)cUser.getSelectedItem();
			
			User user = new User();
			user.setLogin(login);
			user.setPassword(pass);
			user.setType(type);
			
			// validates login and pass, if true logs in
			if(UserLogic.getInstance().login(user)){
				frame.setLogin(login);
				frame.setUserState(mapUserStates(type));
			}
		}
		
	}
}
